var Promise = require('bluebird');
var LabelInfo = require('mongoose').model('Label');
var Station = require('mongoose').model('Station');
var HistoryInfo = require('mongoose').model('LabelHistory');

function saveHistory(id, updateId, history, cb) {
    var info = {id: id, nodeID: updateId, updateDate: new Date().getTime()};
    info.beforeUpdateInfo = history.beforeUpdate;
    info.afterUpdateInfo = history.afterUpdate;
    HistoryInfo.create(info, function (err, data) {
        if (err) {
            console.log(err);
            return cb({status: false, message: '记录历史失败'})
        }
        cb({status: true, message: data})
    });
}

function saveDelHistory(id, updateId, cb) {
    var info = {id: id, nodeID: updateId, updateDate: new Date().getTime(), delete: true};

    HistoryInfo.create(info, function (err, data) {
        if (err) {
            console.log(err);
            return cb({status: false, message: '记录历史失败'})
        }
        cb({status: true, message: data})
    });
}

module.exports = {
    update: function (query, info, history) {
        var defer = Promise.defer();
        Station.where({$or: [{nodeID: info.nodeID}]}).exec()
            .then(function (result) {

                LabelInfo.where({$or: [{nodeID: info.nodeID}]}).exec()
                    .then(function (label) {

                        if ((label.length === 0 || (label.length === 1 && info.nodeID == query.nodeID)) && result.length === 0) {
                            LabelInfo.update(query, info).exec(function (err, data) {
                                if (err) {
                                    return defer.reject('update error')
                                } else {
                                    history.afterUpdate = info;
                                    LabelInfo.findOne({nodeID: info.nodeID}).exec(function (err, data) {
                                        if (err) {
                                            return defer.reject('get station error')
                                        }
                                        saveHistory(data._id, info.nodeID, history, function (data) {
                                            defer.resolve({status: true, message: data})
                                        });
                                    })
                                }
                            });
                        } else {
                            defer.resolve({status: false, message: 'id 已存在'})
                        }
                    })
            })
        return defer.promise
    },
    delete: function (id) {
        var defer = Promise.defer();
        LabelInfo.findOne({nodeID: id}).exec(function (err, data) {
            if (err) {
                return defer.reject('delete station error')
            }
            if (!data) {
                return defer.resolve({status: false, message: 'station not exist'})
            } else {
                var dataId = data._id;
                data.remove(function (err) {
                    saveDelHistory(dataId, id, function (result) {
                        defer.resolve({status: true})
                    })
                })
            }
        });
        return defer.promise
    },
    all: function () {
        var defer = Promise.defer();
        LabelInfo.where().exec(function (err, data) {
            if (err) {
                defer.reject('find all station error')
            } else {
                defer.resolve(data)
            }
        });
        return defer.promise;
    },
    create: function (label) {
        var defer = Promise.defer();
        LabelInfo.where({$or: [{nodeID: label.nodeID}]}).exec()
            .then(function (result) {

                Station.where({$or: [{nodeID: label.nodeID}]}).exec()
                    .then(function (station) {

                        if (result.length === 0 && station.length === 0) {
                            // label.nodeType = 3;
                            console.log("label 信息:"+JSON.stringify(label))
                            LabelInfo.create(label, function (err, data) {
                                if (err) {
                                    return defer.reject('创建失败')
                                }
                                saveHistory(data._id, data.nodeID, {
                                    beforeUpdate: null,
                                    afterUpdate: data
                                }, function () {
                                    defer.resolve({status: true, message: data})
                                });
                            });
                        } else {
                            defer.resolve({status: false, message: '标签已存在'})
                        }
                    })
            });
        return defer.promise;
    }
};